package com.time.company.components.login;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BasePW;
import com.time.company.components.popup.ChoosePW;
import com.time.company.components.popup.ImagePW;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.login.ChooseType;
import com.time.company.servermodel.login.SubmitCompanyPara;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ScreenUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.helper.picasso.PicassoImageLoader;
import com.time.company.webserver.listener.ResponseCallback;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 手动注册提交公司信息
 * Created by Bing on 2017/10/28.
 * E-mail is tx16bing@163.com
 */

public class CompanyActivity extends BaseActivity implements View.OnClickListener {

    private static final int COMPANY_INFO_REQUEST_CODE = 122;
    private LinearLayout llParent;
    private RoundedImageView rivLogo;
    private EditText etBusiness, etCharacter, etScale, etAddress;
    private TextView tvCharacterChoice, tvScaleChoice, tvLicense;
    private Button btnSubmit;
    private ImageView ivCheck;

    private boolean isCheck, isLogo;

    private WindowManager.LayoutParams attributes;
    private ImagePW imagePW;
    private ChoosePW choosePW;
    private List<String> mCharacters = new ArrayList<>();
    private List<String> mScales = new ArrayList<>();

    private Request request;
    private static final int CHOOSE_TYPE_WHAT = 11;

    private SubmitCompanyPara mPara;
    private String logoUrl = "0", licenseUrl = "0";

    public static void start(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, CompanyActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company, "");
        assignViews();
        chooseRequest();
    }

    private void assignViews() {
        llParent = findView(R.id.ll_company_parent);
        rivLogo = findView(R.id.riv_company_logo);
        etBusiness = findView(R.id.et_company_business);
        etCharacter = findView(R.id.et_company_character);
        etScale = findView(R.id.et_company_scale);
        etAddress = findView(R.id.et_company_registered_address);
        tvCharacterChoice = findView(R.id.tv_company_character_choose);
        tvScaleChoice = findView(R.id.tv_company_scale_choose);
        tvLicense = findView(R.id.tv_company_license);
        btnSubmit = findView(R.id.btn_submit);
        ivCheck = findView(R.id.iv_agree_register);

        rivLogo.setOnClickListener(this);
        tvCharacterChoice.setOnClickListener(this);
        tvScaleChoice.setOnClickListener(this);
        tvLicense.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        ivCheck.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.riv_company_logo:
                isLogo = true;
                if (imagePW == null || !imagePW.isShowing()) {
                    launchImage();
                } else {
                    return;
                }
                break;

            case R.id.tv_company_license:
                isLogo = false;
                if (imagePW == null || !imagePW.isShowing()) {
                    launchImage();
                } else {
                    return;
                }
                break;

            case R.id.tv_company_character_choose:
                if (choosePW == null || !choosePW.isShowing()) {
                    if (this.mCharacters.isEmpty()) {
                        String[] character = resources.getStringArray(R.array.company_character);
                        mCharacters = new ArrayList<>();
                        for (int i = 0; i < character.length; i++) {
                            mCharacters.add(character[i]);
                        }
                    }
                    launchChoose(resources.getInteger(R.integer.pw_type_character), this.mCharacters, etCharacter.getText().toString());
                } else {
                    return;
                }
                break;

            case R.id.tv_company_scale_choose:
                if (choosePW == null || !choosePW.isShowing()) {
                    if (this.mScales.isEmpty()) {
                        String[] scale = resources.getStringArray(R.array.company_scale);
                        mScales = new ArrayList<>();
                        for (int i = 0; i < scale.length; i++) {
                            mScales.add(scale[i]);
                        }
                    }
                    launchChoose(resources.getInteger(R.integer.pw_type_scale), this.mScales, etScale.getText().toString());
                } else {
                    return;
                }
                break;

            case R.id.btn_submit:
                if (!checkForm()) {
                    return;
                }
                mPara = new SubmitCompanyPara();
                mPara.setLogoUrl(logoUrl);
                mPara.setMainBusiness(etBusiness.getText().toString());
                mPara.setCompanyNature(etCharacter.getText().toString());
                mPara.setScale(etScale.getText().toString());
                mPara.setAddress(etAddress.getText().toString());
                mPara.setLicenseUrl(licenseUrl);
                CompanyInfoActivity.start(this, COMPANY_INFO_REQUEST_CODE, mPara);
                break;

            case R.id.iv_agree_register:
                ivCheck.setImageResource(isCheck ? R.drawable.iv_protocol_select_normal : R.drawable.iv_protocol_selected);
                isCheck = !isCheck;
                break;

            default:
                break;
        }

    }

    private boolean checkForm() {
        boolean isFormValid = true;

        if (TextUtils.isEmpty(logoUrl)) {
            ToastUtils.showShort("请上传公司图片");
            isFormValid = false;
        } else if (TextUtils.isEmpty(etBusiness.getText().toString())) {
            ToastUtils.showShort("请输入主营业务");
            isFormValid = false;
        } else if (TextUtils.isEmpty(etCharacter.getText().toString())) {
            ToastUtils.showShort("请输入企业性质");
            isFormValid = false;
        } else if (TextUtils.isEmpty(etScale.getText().toString())) {
            ToastUtils.showShort("请输入人数规模");
            isFormValid = false;
        } else if (TextUtils.isEmpty(etAddress.getText().toString())) {
            ToastUtils.showShort("请输入注册地址");
            isFormValid = false;
        } else if (TextUtils.isEmpty(licenseUrl)) {
            ToastUtils.showShort("请上传营业执照");
            isFormValid = false;
        } else if (!isCheck) {
            ToastUtils.showShort("请同意上述协议");
            isFormValid = false;
        }

        return isFormValid;
    }

    /**
     * 获取注册选取的条目
     */
    private void chooseRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_getRegisterChooseTypeList));
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, CHOOSE_TYPE_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    private void launchChoose(int mType, List<String> data, String choose) {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        choosePW = new ChoosePW(this, llParent, data, mType, choose);
        choosePW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(final int type, String result) {
                if (type == resources.getInteger(R.integer.pw_type_character)) {
                    etCharacter.setText(result);
                } else {
                    etScale.setText(result);
                }
            }
        });
        choosePW.showAtLocation(llParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        choosePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    /**
     * 选择图片
     */
    private void launchImage() {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        imagePW = new ImagePW(this, llParent, resources.getInteger(R.integer.pw_type_head));
        imagePW.setOnItemClickListener(new BasePW.OnItemClickListener() {
            @Override
            public void onItemClick(final int type, Object result) {
                if (type == resources.getInteger(R.integer.pw_image_one)) {
                    // 拍照
                    Album.camera(CompanyActivity.this) // 相机功能。
                            .image() // 拍照。
                            // .filePath() // 文件保存路径，非必须。
                            .requestCode(2)
                            .onResult(new Action<String>() {
                                @Override
                                public void onAction(int requestCode, @NonNull String result) {
                                    if (isLogo) {
                                        int size = ScreenUtils.dip2px(60);
                                        PicassoImageLoader.loadImageViewSizeNoCache(CompanyActivity.this,
                                                result,
                                                size,
                                                size,
                                                R.drawable.iv_default_92_68,
                                                R.drawable.iv_default_92_68,
                                                toString(), rivLogo);
                                    }
                                    uploadFile(result);
                                }
                            })
                            .onCancel(new Action<String>() {
                                @Override
                                public void onAction(int requestCode, @NonNull String result) {
                                    // 用户取消了操作。
                                }
                            })
                            .start();
                } else {
                    // 相册

                    // 表示相册的存储的权限申请通过
                    Album.image(CompanyActivity.this) // 选择图片。
                            .multipleChoice()
                            .requestCode(200)
                            .camera(false)
                            .columnCount(3)
                            .selectCount(1)
                            .widget(Widget.newDarkBuilder(CompanyActivity.this)
                                    .title("图片")
                                    .statusBarColor(ContextCompat.getColor(application, R.color.colorStatusBar))
                                    .toolBarColor(ContextCompat.getColor(application, R.color.colorStatusBar))
                                    .navigationBarColor(ContextCompat.getColor(application, R.color.colorStatusBar)) // Android5.0+的虚拟导航栏颜色。
                                    .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                                    .bucketItemCheckSelector(
                                            ContextCompat.getColor(application, R.color.colorPrimary),
                                            ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                                    .build())
                            .onResult(new Action<ArrayList<AlbumFile>>() {
                                @Override
                                public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                    if (isLogo) {
                                        int size = ScreenUtils.dip2px(60);
                                        PicassoImageLoader.loadImageViewSizeNoCache(CompanyActivity.this,
                                                result.get(0).getThumbPath(),
                                                size,
                                                size,
                                                R.drawable.iv_default_92_68,
                                                R.drawable.iv_default_92_68,
                                                toString(), rivLogo);
                                    }
                                    uploadFile(result.get(0).getPath());
                                }
                            })
                            .onCancel(new Action<String>() {
                                @Override
                                public void onAction(int requestCode, @NonNull String result) {
                                }
                            })
                            .start();

                }
            }
        });
        imagePW.showAtLocation(llParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        imagePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    /**
     * 上传图片文件
     *
     * @param path
     */
    private void uploadFile(String path) {
        if (!NetWorkUtils.isNetAvailable(application)) {
            ToastUtils.showShort(application.getString(R.string.network_error));
            return;
        }
        if (TextUtils.isEmpty(path)) {
            ToastUtils.showShort(getString(R.string.upload_valid_path));
            return;
        }

        LoginParameters parameters = new LoginParameters();
        parameters.setCommand(getString(R.string.command_uploadFile));
        parameters.setType(isLogo ? getString(R.string.upload_company_logo) : getString(R.string.upload_company_license));


        String url = null;
        try {
            url = new StringBuilder().append(AddressManager.getInstance().getAddress())
                    .append("?").append(getString(R.string.command))
                    .append("=").append(getString(R.string.command_uploadFile))
                    .append("&").append(getString(R.string.data))
                    .append("=").append(URLEncoder.encode(new Gson().toJson(parameters), "UTF-8"))
                    .toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Request request = NoHttp.createStringRequest(url, RequestMethod.POST);
        request.add(application.getString(R.string.command), parameters.getCommand());
        request.add(application.getString(R.string.platform), parameters.getPlatform());
        request.add("type", isLogo ? getString(R.string.upload_company_logo) : getString(R.string.upload_company_license));
        File file = new File(path);
        BasicBinary fileBinary = new FileBinary(file);
        request.add("fileInput", fileBinary);
        request.setCancelSign(toString());
        WebServerManager.getInstance().add(this, request, new ResponseCallback<String>() {
                    @Override
                    public void onSucceed(int what, Response<String> response) {
                        String bean = response.get();
                        BasicBean basicBean = new Gson().fromJson(bean, BasicBean.class);

                        if (basicBean == null) {
                            return;
                        }

                        if (basicBean.isSuccess()) {
                            Snackbar.make(llParent, getString(R.string.upload_sc), Snackbar.LENGTH_SHORT).show();
                        } else {
                            Snackbar.make(llParent, getString(R.string.upload_failure), Snackbar.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
                        Snackbar.make(llParent, getString(R.string.upload_failure), Snackbar.LENGTH_SHORT).show();
                    }
                },
                409, true, false, true);
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;
        if (basicBean.isSuccess()) {
            if (what == CHOOSE_TYPE_WHAT) {
                ChooseType chooseType = basicBean.parseData(ChooseType.class);
                if (chooseType == null) return;
                List<ChooseType.CompanyNatureListBean> companyNatureList = chooseType.getCompanyNatureList();
                List<ChooseType.ScaleListBean> scaleList = chooseType.getScaleList();

                if (null != companyNatureList) {
                    for (ChooseType.CompanyNatureListBean nature : companyNatureList) {
                        this.mCharacters.add(nature.getName());
                    }
                }

                if (null != scaleList) {
                    for (ChooseType.ScaleListBean scale : scaleList) {
                        this.mCharacters.add(scale.getName());
                    }
                }
            }
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == COMPANY_INFO_REQUEST_CODE){
            if (resultCode == RESULT_OK){
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != imagePW) {
            imagePW.dismiss();
            imagePW = null;
        }

        if (null != choosePW) {
            choosePW.dismiss();
            choosePW = null;
        }

        if (null != mPara) {
            mPara = null;
        }
    }
}
